import { getZkxmxxList, MAGIC_SUCC_CODE } from "@api"
import { addLisYqxm } from "../../../api/zkxm"

export function use() {
  const yqid = ref<string>(''),
    tableData = ref<any[]>([]),
    currentRow = ref<any>(),
    addShow = ref<boolean>(false),
    addFormData = ref({ jsm: '12' }),
    formTable = ref(),
    addModule = ref()
  watch(() => yqid.value, query)
  function setFormData(data: any) {
    tableData.value = data
    nextTick(() => {
      if (formTable.value) {
        formTable.value.layout()
      }
    })
  }
  function query() {
    const id = yqid.value
    if (id) {
      getZkxmxxList({ yqid: id }).then(({ data: { list } }) => {
        setFormData(list)
      })
    } else {
      tableData.value = []
    }
  }
  function add() {
    const id = yqid.value
    if (id) {
      addShow.value = true
    } else {
      ElMessage({ type: 'warning', message: '请先选择要操作的仪器' })
    }
  }
  function addRest() {
    addFormData.value = {} as any
  }
  function del() {
    const obj = currentRow.value
    if (obj) {
      const { zbid } = obj
      setFormData(tableData.value.filter(it => it.zbid != zbid))
    } else {
      ElMessage({ type: 'warning', message: '请选择要删除的项目' })
    }
  }
  function sure(data: any[]) {
    const filter = data.filter((it) => {
      return tableData.value.filter(cs => {
        return cs.zbid == it.zbid
      }).length
    })
    if (filter.length) {
      ElMessage({ type: 'warning', message: '以下数据：【' + filter.map(it => it.zbmc).join('】,【') + '】重复出现，请重新选择' })
      return
    }
    setFormData(tableData.value.concat(data || []))
    if (addModule)
      addModule.value.clear()
    addShow.value = false
  }
  function save() {
    addLisYqxm({ data: tableData.value, yqid: yqid.value }).then(({ code, data, message }) => {
      if (code === MAGIC_SUCC_CODE) {
        ElMessage({ type: 'success', message: '新增成功' })
        query()
      } else
        ElMessage({ type: 'warning', message })
    })
  }
  return { yqid, tableData, del, currentRow, query, save, add, addShow, addFormData, addRest, sure, formTable, addModule }
}